package ysc.cqnu.operdb.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ysc.cqnu.operdb.entity.ResultData;
import ysc.cqnu.operdb.entity.ResultUserInfo;
import ysc.cqnu.operdb.mapper.UserMapper;
import ysc.cqnu.operdb.service.UploadImgService;

import java.io.File;
import java.io.FileOutputStream;

@Service
public class UploadImgServiceImpl implements UploadImgService {
    @Autowired
    private ResultData resultData;
    @Autowired
    private ResultUserInfo resultLogin;
    @Autowired
    private UserMapper userMapper;
    @Override
    public ResultData uploadImgService(String name,MultipartFile adImage,String age,String sex,String emile) {
        String fileName = adImage.getOriginalFilename();

        //判断是否是.***格式
        int start = fileName.indexOf(".");
        if (start==-1){
            resultData.flag="typeError";
            resultData.data=null;
            return resultData;
        }

        //判断是不是图片
        String type = fileName.substring(start+1);
        if((!"jpg".equals(type))&&(!"png".equals(type))&&(!"bmp".equals(type))&&(!"JPG".equals(type))&&(!"jpeg".equals(type))){
            resultData.flag="typeError";
            resultData.data=null;
            return resultData;
        }

        //图片存入的绝对路径
        String filePath = "E://up360/apache-tomcat-9.0.37/webapps/img/";
        File targetFile = new File(filePath);

        //将图片命名为 用户名+.***
        fileName = name+"."+type;

        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath+fileName);
            out.write(adImage.getBytes());
            out.flush();
            out.close();
            resultData.flag="ImgSuccess";
            resultLogin.userImgSrc="http://192.168.43.161:8080/img/"+fileName;
            resultLogin.age=age;
            resultLogin.sex=sex;
            resultLogin.emile=emile;
            //写入数据库
            userMapper.updateUserImg(resultLogin.userImgSrc,name,age,sex,emile);
            resultData.data=resultLogin;

        } catch (Exception e) {
            e.printStackTrace();
            resultData.flag="ImgFail";
            resultData.data=null;
            return resultData;
        }
        return resultData;
    }
}
